import datetime

from django.http import *

from rest_framework.decorators import action
from rest_framework.response import Response

from homes.models import House
from orders.models import Order
from settings import QINIU_URL
from utils import response_code



from rest_framework.viewsets import ModelViewSet

from orders.serializer.order import OrderSerializer, OrderInfoSerializer
# from orders.serializer.order import OrderSerializer, HouseOrderSerializer
from rest_framework import status
from django.views.decorators.csrf import csrf_exempt

#　创建订单
class OrderViewset(ModelViewSet):
    serializer_class = OrderSerializer

    queryset = Order.objects.all()

    @csrf_exempt
    def create(self, request, *args, **kwargs):
        user = request.user
        user_id = user.id

        # for i in request.data.keys():
        #     i = eval(i)
        house_id = request.data.get('house_id')
        # user_id = request.data.get('user_id')
        start_date = request.data.get('begin_date')
        end_date = request.data.get('end_date')
        if not all([house_id,start_date,end_date]):
            return HttpResponseForbidden('缺少必传参数')
        house = House.objects.get(id=house_id,room_count__gt=0)
        if house.user.id == user.id:
            return Response({'errno':response_code.RET.DATAEXIST,'errmsg':'您不能预购自己的房子'})

        new_time = datetime.date.today()
        if house.room_count >0:
            order = Order.objects.filter(house_id = house_id,end_date__gt=new_time,user_id=user_id)
            if order:
                return Response({'errno':response_code.RET.DATAEXIST,'errmsg':'您已经预定该房间预定'})
        else:
            return Response({'errno': response_code.RET.DATAEXIST, 'errmsg': '该房子没房间了'})

        # 数据库逻辑
        # 查询数据库所需要的数据
        start_date = datetime.datetime.strptime(start_date,'%Y-%m-%d')
        end_date = datetime.datetime.strptime(end_date,'%Y-%m-%d')
        days = (end_date - start_date).days
        print(days)
        if days ==0:
            days= 1
        elif days < house.min_days:
            return Response({'errno': response_code.RET.DATAEXIST, 'errmsg': '该房间最少入住%s天'%house.min_days})
        # 创建订单
        orders = Order.objects.create(
            user_id = user_id,
            house_id = house_id,
            begin_date = start_date,
            end_date = end_date,
            days = days,
            house_price = 0,
            amount = 0,
            status = Order.ORDER_STATUS["WAIT_ACCEPT"],
        )

        orders.house_price = orders.house.price
        orders.amount = orders.house_price * days + house.deposit
        # orders.amount = orders.house_price * days
        house.room_count -=1
        # 下单完成的订单数
        house.order_count +=1
        orders.save()
        house.save()
        return Response({ "data": {"order_id": orders.id},"errno": "0","errmsg": "下单成功"})


    # 评论
    @action(methods=["PUT"], detail=True)
    def comment(self, request, pk):
        order = self.get_object()
        for i in request.data.keys():
            i = eval(i)
            comments = i.get('comment')
            order.comment = comments
            order.save()
            return Response({"errno": "0", "errmsg": "操作成功"})


    @action(methods=['PUT'],detail=True)
    def status(self,request,pk):
        order = self.get_object()
        if order.status != 0:
            return Response({'errno': response_code.RET.DATAEXIST, 'errmsg': '必须是新订单哦'})

        for i in request.data.keys():
            i= eval(i)
            print(type(i))
            actions = i.get('action')
            reason = i.get('reason')
            if actions == 'accept':
                order.status = Order.ORDER_STATUS["WAIT_PAYMENT"]
            elif actions =='reject':
                order.status=Order.ORDER_STATUS['REJECTED']
                order.house.room_count +=1
                order.comment = reason
            order.save()
            order.house.save()
            return Response({"errno":"0","errmsg":"操作成功"})
        else:
            Response(status=status.HTTP_403_FORBIDDEN)


class OrderInfoView(ModelViewSet):
    serializer_class = OrderInfoSerializer

    def get_queryset(self):
        user = self.request.user
        role = self.request.query_params.get("role")
        if role == 'landlord':
            # 一查多查看 用户有那些房子以及相关的订单
            house = user.houses.all()
            queryset = Order.objects.filter(house=house).order_by('-create_time')
            return queryset
        else:
            queryset = Order.objects.filter(user_id=user.id).order_by('-create_time')
            return queryset
    # 判断用户是谁  根据是谁 修改订单数据
    def list(self, request, *args, **kwargs):

        orders = super().list(request).data
        data = {}
        data_list =[]

        for order in orders:
            orderq = Order.objects.get(id=order['id'])
            order['status'] = Order.ORDER_STATUS_ENUM[order['status']]
            order['order_id'] = order['id']
            order['start_date'] = order['begin_date']
            del order['begin_date']
            # del order['id']
            order['img_url'] =QINIU_URL+  orderq.house.index_image_url
            order['title'] = orderq.house.title
            data_list.append(order)
        data['orders'] = data_list
        return Response({"data":data,"errmsg": "OK",
    "errno": "0"})




